<!--
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2022-04-07 20:18:30
 * @LastEditors: Sam
 * @LastEditTime: 2022-05-07 09:58:07
-->
<template>
    <div class="app-container">
        <el-card>
            <div slot="header" class="clearfix">
                <span>商品规格模板</span>
            </div>
             <div class="filter-container">
                <el-input v-model="listQuery.cate_name" placeholder="请输入分类名称" clearable style="width: 200px;margin-right: 10px;margin-bottom:10px" class="filter-item" @keyup.enter.native="handleFilter" />

                <el-button v-waves  class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                {{ '搜索' }}
                </el-button>
                 <el-button v-waves :disabled="!checkPermission(['goods.category_create'])"  class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
                    {{ "添加" }}
                </el-button>
                
                
                
            </div>
             <el-table
                v-loading="listLoading"
                :header-cell-style="{background:'#eef1f6',color:'#606266'}"
                :data="list"
                border
                fit
                highlight-current-row
                style="width: 100%"
                size="mini"
                >  
            <el-table-column  align="center" label="编号">
                <template slot-scope="scope">
                    <span>{{ scope.row.id }}</span>
                </template>
            </el-table-column>
            <el-table-column  align="center" label="规则名称">
                <template slot-scope="scope">
                    <span>{{ scope.row.rule_name }}</span>
                </template>
            </el-table-column>
            <el-table-column  align="center" label="商品规格">
                <template slot-scope="scope">
                    <span v-for="(item,idx) in scope.row.attr_name" :key="idx"> {{ item }}</span>
                </template>
            </el-table-column>
            <el-table-column  align="center" label="商品属性">
                <template slot-scope="scope">
                    <span>{{ scope.row.attr_value }}</span>
                </template>
            </el-table-column>

                <el-table-column align="center" width="250" :label="'操作'">
                <template slot-scope="scope">
                    
                    <el-button v-waves v-permission="['goods.rule_edit']"  type="primary"  size='mini' icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">
                        {{ "编辑" }}
                    </el-button>
                    <el-button v-waves v-permission="['goods.rule_delete']"  type="danger" :destroy-on-close="true" size='mini' icon="el-icon-delete" @click="handleDelete(scope.$index, scope.row)">
                        {{ "删除" }}
                    </el-button>
                </template>
                </el-table-column>
            </el-table>

            <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
        </el-card>
           <el-dialog :title="'编辑'" :visible.sync="dialogVisible" @close="getList" :close-on-click-modal=false>
          
         </el-dialog>
        <el-dialog :title="'添加'" :visible.sync="dialogVisible" @close="getList"  :close-on-click-modal=false>
            <el-form :model="form_data"   ref="form" label-width="120px" class="demo-ruleForm">
                    <el-form-item label="模板名称" prop="title">
                        <el-input v-model="form_data.rule_name" placeholder="请输入模板名称" clearable></el-input>
                    </el-form-item>
                    <div v-for="(item,index) in items" :key="index">
                        <el-tag closable  type="success" style="margin-bottom:10px;margin-left:120px;"  @close="deleteItem(index)" >{{item.value}}</el-tag>
                        <div style="display:flex;align-items:center;margin-left:120px;">
                            <el-tag closable style="margin-bottom:10px;margin-right:5px;" size="small" v-for="(val,inx) in item.detail" :key="inx" @close="deleteValue(item,inx)" >{{val}}
                            </el-tag>
                            <el-input v-model="item.detailValue" size="mini" style="width:120px;margin-bottom:10px" clearable placeholder="请输入"></el-input>
                             <el-button type="text"  @click="addDetail(item)" style="margin-bottom:10px;margin-left:22px">添加</el-button>
                        </div>
                    </div>
                    
                    <div style="display:flex;align-items:center" v-if="newRule">
                        <el-form-item label="规格">
                            <el-input  v-model="formDynamic.attrsName" placeholder="请输入规格" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="规格值：">
                            <el-input v-model="formDynamic.attrsVal" placeholder="请输入规格值" clearable></el-input>
                        </el-form-item>
                        <el-button type="text"  @click="createAttrName" style="margin-bottom:22px;margin-left:22px">添加</el-button>
                        <el-button type="text" @click="newRule = false"  style="margin-bottom:22px">取消</el-button>
                    </div>
                    <el-form-item v-if="newRule == false">
                       <el-button type="primary"  @click="newRule = true">添加新规格</el-button>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitForm('form')">确 定</el-button>
                </div>
        </el-dialog>
    </div>
</template>
<style scoped>
    .import {
        display: inline-block;
        margin-left: 5px;
    }
</style>
<script>
    import waves from '@/directive/waves' // waves directive
    import permission from '@/directive/permission/index.js' // 权限判断指令
    import checkPermission from '@/utils/permission' // 权限判断函数
    import { list, detail, del,create,edit } from '@/api/goods_rule' // api接口
    import { parseTime } from '@/utils' // 时间格式化函数
    import { getToken } from '@/utils/auth' // 获取token
    import Pagination from '@/components/Pagination' // 分页组件
    export default{
        name: 'rule_index',
        components: { Pagination }, // 引入组件
        filters: {
            parseTime // 时间过滤器
        },
        directives: { waves, permission }, // 引入指令
          data() {
            return {
             headerObj: {
                'Authorization': 'Bearer ' + getToken()
            },
            // 规格数据
            formDynamic: {
                attrsName: '',
                attrsVal: ''
            },
            items: [],
            newRule: false,
            form_data:{
                rule_name: '',    
                id: '',         
            },
  
            list: null, // 列表数据
            total: 0, // 总条数
            select_ids : [], // 选中的id集合
            listLoading: true, //加载loadig
            listQuery: { //列表查询参数
                page: 1,
                limit: 10
            },
            dialogVisible:false
            }
        },
          created() {
            this.getList()
        },
        methods: {

            /**
             * 给某个属性添加属性值
             * @param item
             * */
            addDetail: function (item) {
                if (!item.detailValue) return false;
                if (item.detail.find(function (val) {
                    if (item.detailValue == val) {
                        return true;
                    }
                })) {
                    return this.showMsg('添加的属性值重复');
                }
                item.detail.push(item.detailValue);
                item.detailValue = '';
                console.log(this.items);
            },
            /**
             * 删除某条属性
             * @param index
             * */
            deleteItem: function (index) {
                this.items.splice(index, 1);
            },
              /**
             * 删除某个属性值
             * @param item 父级循环集合
             * @param inx 子集index
             * */
            deleteValue: function (item, inx) {
                if (item.detail.length > 1) {
                    item.detail.splice(inx, 1);
                } else {
                   this.$message.error('请设置至少一个属性');
                }
            },

            
            /**
             * 创建属性
             * */
            createAttrName: function () {
                if (this.formDynamic.attrsName && this.formDynamic.attrsVal) {
                    if (this.items.find(function (val) {
                        if (val.value == this.formDynamic.attrsName) {
                            return true;
                        }
                    }.bind(this))) {
                        this.$message.error('添加的属性重复');
                    }
                    this.items.push({
                        value: this.formDynamic.attrsName,
                        detail: [this.formDynamic.attrsVal]
                    });
                    this.formDynamic.attrsName = '';
                    this.formDynamic.attrsVal = '';
                    this.newRule = false;
                } else {
                    this.$message.error('请添加完整的规格');
                }
            },

            checkPermission, // 权限判断函数
            handleFilter() { // 查询
                this.listQuery.page = 1
                this.getList()
            },
            handleCreate() { // 新增对话框显示
              this.dialogVisible = true
            },
            handleEdit(index, row) { // 编辑对话框显示
              this.dialogVisible = true
              this.get_detail(row.id);
              this.form_data.id = row.id
            },
            get_detail(id){
                detail(id).then(res => {
                    this.form_data.rule_name = res.data.rule_name;
                    this.items = res.data.rule_value;
                    this.newRule = false;
                })},
            submitForm(formName) { 
                if(this.form_data.id){
                    edit({
                        id: this.form_data.id,
                        rule_name: this.form_data.rule_name,
                        rule_value: this.items
                    }).then(res => {
                        this.$message.success('编辑成功')
                        this.dialogVisible = false;
                        this.form_data.rule_name = '',
                        this.items = []
                    })
                }else{
                  create({
                    rule_name: this.form_data.rule_name,
                    rule_value: this.items
                }).then(res => {
                        this.$message.success('添加成功')
                        this.dialogVisible = false;
                        this.form_data.rule_name = '',
                        this.items = []
                        })
                }
            },
            handleDelete(index, row) { // 删除
                    const thiz = this
                    this.$confirm('确认要删除吗？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        del(row.id).then(() => {
                        this.$message({
                            message: '删除成功',
                            type: 'success',
                            duration: 1500,
                            onClose() {
                                thiz.list.splice(index, 1)
                            }
                        })
                        })
                    }).catch(() => {

                    })
                },
            getList() { // 获取列表
                this.listLoading = true
                list(this.listQuery).then(response => {
                        this.list = response.data.data
                        this.total = response.data.total
                        this.listLoading = false
                    })
                },
            }
    }
</script>

